package edu.whu;

import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.core.io.ClassPathResource;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Properties;

/**
 * @author guanruwang
 * @date 2023/9/21$
 */
public class Main {
    public static Object getObjectbyProperties(String path){
        try{
            Properties properties = PropertiesLoaderUtils.loadProperties(new ClassPathResource(path));
            String classname = properties.getProperty("bootstrapClass");
            Class myclass = Class.forName(classname);
            Object o = myclass.newInstance();

            return o;
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    public static void init(Object o) {
        Method[] methods = o.getClass().getDeclaredMethods();
        try{
            for(Method method : methods){
                if(method.isAnnotationPresent(InitMethod.class)){
                    method.setAccessible(true);
                    method.invoke(o);
                }
            }
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (IllegalArgumentException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {

        init(getObjectbyProperties("/myapp.properties"));

    }
}